package com.ktjy.iotorder.controller;

import com.ktjy.iotorder.pojo.User;
import com.ktjy.iotorder.service.MySelfClient;
import com.ktjy.iotorder.service.OrderClient;
import com.ktjy.pojo.DeviceData;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

@Slf4j
@RestController
//@RefreshScope
public class OrderController {

    @Autowired
    RestTemplate restTemplate;

    @Autowired
    DiscoveryClient discoveryClient;

    @Autowired
    OrderClient orderClient;

    @Autowired
    MySelfClient mySelfClient;

    @Autowired
    User user;

    @Value("${myapp.user.name}")
    private String name;

    @Value("${myapp.user.age}")
    private String age;


    @GetMapping("/nacosconfig")
    public String nacosconfig() {
        return name + " " + age;
    }

    @GetMapping("/user")
    public User user() {
        System.out.println(user);
        return user;
    }

    @GetMapping("/order/{id}")
    public DeviceData order(@PathVariable Integer id) {
        //ResponseEntity<String> forEntity = restTemplate.getForEntity("http://localhost:7031/product/" + id, String.class);
        //从nacos中获取服务地址
        //ServiceInstance serviceInstance = discoveryClient.getInstances("iot-product-7031").get(0);
        //String url = serviceInstance.getHost() + ":" + serviceInstance.getPort();
        //String url = "iot-product";
        //log.info("url:" + url);
        //restTemplate 编程式
        //ResponseEntity<DeviceData> forEntity = restTemplate.getForEntity("http://" + url + "/product/" + id, DeviceData.class);
        DeviceData product = orderClient.getProduct(id);
        return product;
    }

    @GetMapping("/order/feign/{id}")
    public String orderFeign(@PathVariable Integer id) {
        String product7032 = mySelfClient.getProduct7032(id);
        return product7032;
    }
}
